import { ref } from 'vue'
import { settingStore } from '@renderer/store/setStore'
import { storeToRefs } from 'pinia'
import _ from 'lodash'
const { ipcRenderer } = require('electron')

export default () => {
    let myApi = ref()
    const openFolder = ref(false)
    const videos: any = ref([])
    const setStoreData = settingStore()
    const { displayMethod, videoFolders, sort } = storeToRefs(setStoreData)
    const playVideoId = ref('')
    const message = ref('loading')

    // 获取视频
    const scanVideo = async (path: string) => {
        videos.value = [];
        message.value = "loading";
        const res = await myApi.value.scanVideoFiles(path);
        if (res.code == 200) {
            // 按名字倒序排序
            if (sort.value == 'asc') videos.value = _.sortBy(res.data, 'name')
            if (sort.value == 'desc') videos.value = _.sortBy(res.data, 'name').reverse()
            message.value = 'success'
        } else {
            message.value = 'error'
        }
    }
    // 获取视频封面函数保持不变
    // const drawVideo = (vdo) => {
    //     return new Promise((resolve) => {
    //         const canvas = document.createElement("canvas");
    //         const ctx = canvas.getContext("2d");
    //         canvas.width = vdo.videoWidth / 10;
    //         canvas.height = vdo.videoHeight / 10;
    //         const frameTime = 1; // 绘制视频开头1秒内的画面
    //         const frameRate = vdo.videoWidth > 0? vdo.videoWidth / vdo.duration : 30; // 简单估算视频帧率（可根据实际情况调整）
    //         const frameCount = Math.min(frameTime * frameRate, vdo.videoWidth); // 计算要绘制的帧数
    //         const frameWidth = vdo.videoWidth / frameCount; // 每帧画面的宽度
    //         for (let i = 0; i < frameCount; i++) {
    //             ctx?.drawImage(vdo, i * frameWidth, 0, frameWidth, vdo.videoHeight,
    //                 i * (canvas.width / frameCount), 0, canvas.width / frameCount, canvas.height);
    //         }
    //         canvas.toBlob((blob) => {
    //             resolve({
    //                 blob,
    //                 url: URL.createObjectURL(blob!)
    //             });
    //             // 删除临时对象，释放内存
    //             canvas.remove();
    //             vdo.pause();
    //             vdo.remove();
    //         });
    //     });
    // }


    const openFolderEvent = (item: any) => {
        scanVideo(item.path)
        openFolder.value = true
    }
    const closeFolderEvent = () => {
        videos.value = []
        playVideoId.value = ''
        openFolder.value = false
    }

    const changeSorting = () => {
        if (sort.value == 'asc') videos.value = _.sortBy(videos.value, 'name')
        if (sort.value == 'desc') videos.value = _.sortBy(videos.value, 'name').reverse()
    }

    const AddFolder = async () => {
        const res = await ipcRenderer.invoke('select-local-file-path')
        if (res.canceled) return
        // 根据路径生成唯一 id 
        const obj = {
            name: res.filePaths[0].split('\\').at(-1),
            path: res.filePaths[0],
            checked: false
        }
        // 判断是否已经存在
        if (videoFolders.value.some(el => el.path === res.filePaths[0])) return
        videoFolders.value.push(obj)
        ipcRenderer.send('update-storage', JSON.stringify(setStoreData.$state), 'setStoreData')
    }

    const Delete = (item) => {
        videoFolders.value = videoFolders.value.filter(el => el.path !== item.path)
        ipcRenderer.send('update-storage', JSON.stringify(setStoreData.$state), 'setStoreData')
    }

    return {
        myApi,
        videos,
        displayMethod,
        playVideoId,
        openFolder,
        videoFolders,
        message,
        ipcRenderer,
        setStoreData,
        openFolderEvent,
        closeFolderEvent,
        changeSorting,
        AddFolder,
        Delete
    }
}